/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.hbzhit.modules.act.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import com.hbzhit.common.entity.ProcessEntity;
import com.hbzhit.common.utils.R;
import com.hbzhit.modules.act.dto.TaskDTO;
import com.hbzhit.modules.act.factory.WorkFlowFactory;
import com.hbzhit.modules.act.handle.WorkFlowQuery;
import com.hbzhit.modules.act.handle.WorkFlowTaskQuery;
import com.hbzhit.modules.act.service.TaskService;
import com.hbzhit.modules.sys.entity.SysDictValEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.util.List;

/**
 * @author lengleng
 * @date 2018/9/28
 */
@Api(tags = {"流程任务接口"})
@RestController
@AllArgsConstructor
@RequestMapping("/act/task")
public class TaskController {
    private final TaskService taskService;
    private final WorkFlowQuery workFlowQuery;
    private final WorkFlowTaskQuery taskQuery;

    @ApiOperation(value = "当前流程进度图")
    @GetMapping("/view/{id}")
    public ResponseEntity viewCurrentImage(@ApiParam(value = "流程任务ID", required = true) @PathVariable String id) {
        InputStream imageStream = taskService.viewByTaskId(id);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity<>(IoUtil.readBytes(imageStream), headers, HttpStatus.CREATED);
    }

    @ApiOperation(value = "当前流程任务")
    @GetMapping("/{processId}")
    public R<TaskDTO> viewTask(@ApiParam(value = "流程实例ID", required = true) @PathVariable String processId) {

        return R.ok(WorkFlowFactory.getTaskByProcessId(processId));
    }

    @ApiOperation(value = "当前流程历史记录")
    @GetMapping("/his/{processId}")
    public R<ProcessEntity> viewHisTask(@ApiParam(value = "流程实例ID", required = true) @PathVariable String processId) {
        ProcessEntity process = new ProcessEntity();
        process.setTaskList(WorkFlowFactory.getHistoricByProcessId(processId));
        TaskDTO taskDTO = new TaskDTO();
        Task task = taskQuery.processInstanceId(processId);
        if (task != null) {
            taskDTO.setTaskId(task.getId());
        } else {
            if (CollectionUtil.isNotEmpty(process.getTaskList())) {
                String processDefId = process.getTaskList().get(0).getProcessDefKey();
                ProcessDefinition pd = workFlowQuery.getProcessDefinition(processDefId);
                taskDTO.setProcessInstanceId(pd.getDeploymentId());
                taskDTO.setProcessDefKey(pd.getId());
            }
        }
        process.setTask(taskDTO);

        return R.ok(process);
    }


    /**
     * 待办统计查询
     */
    @ApiOperation(value = "待办统计查询")
    @GetMapping("/countTask/{tableName}")
    public R<Integer> countTask(@ApiParam(value = "业务表名", required = true) @PathVariable String tableName) {
        Integer count = taskService.countTask(tableName);

        return R.ok(count);
    }

    /**
     * 类型待办统计查询
     */
    @ApiOperation(value = "类型待办统计查询")
    @GetMapping("/countTypeTask/{tableName}/{typeField}/{typeCode}")
    public R<List<SysDictValEntity>> countTypeTask(@ApiParam(value = "业务表名", required = true) @PathVariable String tableName,
                                               @ApiParam(value = "类型字段名", required = true) @PathVariable String typeField,
                                               @ApiParam(value = "类型编码", required = true) @PathVariable String typeCode) {
        List<SysDictValEntity> list = taskService.countTypeTask(tableName, typeField, typeCode);

        return R.ok(list);
    }

}
